package dao

import (
	"database/sql"
	"fmt"
	"gorm.io/gorm"
	"micro-grpc-server/services/wechat/internal/models"
	wechat "micro-grpc-server/services/wechat/proto"
	"strings"
	"time"
)

// 获取用户列表
func (d *WechatDao) UserList(rq *wechat.ListUserRequest) (list []*models.User, total int64, err error) {
	var query *gorm.DB
	query = d.Db.Table(d.getUserTableName(rq.Scenario))
	if len(rq.Name) > 0 {
		query.Where("name = ?", rq.Name)
	}
	if rq.StartTime > 0 {
		query.Where("time_subscribe >= ?", rq.StartTime)
	}
	if rq.EndTime > 0 {
		query.Where("time_subscribe <= ?", rq.EndTime)
	}
	if len(rq.IsFollow) > 0 {
		switch rq.IsFollow {
		case "y":
			query.Where("is_follow = ?", "Y")
		case "n":
			query.Where("is_follow = ?", "N")
		}
	}
	if rq.TagId > 0 {
		// TODO 这里要join表
	}
	// 获取total
	query.Count(&total)

	if rq.Page > 0 && rq.Limit > 0 {
		query.Limit(int(rq.Limit)).Offset(int(rq.Page-1) * int(rq.Limit))
	}
	if err := query.Find(&list).Error; err != nil {
		return list, total, err
	}
	return
}

// 通过 userid list 获取用户列表
func (d *WechatDao) FindListByUserList(scenario string, userList []string) (list []*models.User, err error) {
	if err := d.Db.Table(d.getUserTableName(scenario)).Where("id in (?)", strings.Join(userList, ",")).Find(&list).Error; err != nil {
		return nil, err
	}
	return
}

// 分批返回
func (d *WechatDao) ScanUserList(rq *wechat.BatchTagBodyRequest) (rows *sql.Rows, err error) {
	tableName := d.getUserTableName(rq.Scenario)
	query := d.Db.Table(tableName)
	if len(rq.Name) > 0 {
		query.Where(fmt.Sprintf("%s.`name` = ?", tableName), rq.Name)
	}
	if len(rq.StartTime) > 0 {
		t, err := time.Parse("2006-01-02 15:04:05", rq.StartTime)
		if err != nil {
			return nil, err
		}
		query.Where("time_subscribe > ?", t.Unix())
	}
	if len(rq.EndTime) > 0 {
		t, err := time.Parse("2006-01-02 15:04:05", rq.EndTime)
		if err != nil {
			return nil, err
		}
		query.Where("time_subscribe < ?", t.Unix())
	}

	switch rq.IsFollow {
	case "y":
		query.Where("is_subscribe = Y")
	case "n":
		query.Where("is_subscribe = N")
	}

	return query.Rows()
}

// 获取场景用户的表名
func (d *WechatDao) getUserTableName(scenario string) string {
	return fmt.Sprintf("%s_wechat_user", scenario)
}
